/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.bfpro.wot.stat;
import java.sql.*;
import java.util.ArrayList;

/**
 *
 * @author fbn
 */
public class Database {

    private Connection conn;

    public Database() throws ClassNotFoundException, SQLException {
        // TODO code application logic here
        // Загрузка драйвера
        Class.forName("org.sqlite.JDBC");
        // Организация соединения
        conn = DriverManager.getConnection("jdbc:sqlite://C:/Temp/~Coding~/Java/wot-stat/wot-stat.sqlite");
        System.out.println("Создали соединение к БД");

    }

    /**
     * Закрыть соединение
     * @throws SQLException
     */
    public void close() throws SQLException {
        conn.close();
    }

    public void create_db() throws SQLException{
        Statement stat = conn.createStatement();

        stat.execute("CREATE TABLE IF NOT EXISTS t_Journal("
                + "id integer primary key, "
                + "f_Timestamp integer, "
                + "f_Data text);");
    }


    public int getRecCount() throws SQLException{
        int recordCount = 0;
        // Объект для sql запросов
        Statement stat = conn.createStatement();

        ResultSet rs = stat.executeQuery("select count(1) from t_Journal;");
        while(rs.next()){
            recordCount = rs.getInt(1);
//            System.out.println("f_Timestamp = " + rs.getString("f_Timestamp"));
 //           System.out.println("f_Data = " + rs.getString("f_Data"));
        }
        //
        rs.close();
        return recordCount;
    }

    public void getCollection() throws SQLException {
        // Объект для sql запросов
        int i = 0;
        Statement stat = conn.createStatement();
        StatData[] coll = new StatData[getRecCount()];
        ResultSet rs = stat.executeQuery("select * from t_Journal;");
        while(rs.next()){
            StatData item = new StatData();
            item.setId(rs.getInt("id"));
            item.setTimestamp(rs.getInt("f_Timestamp"));
            item.setData(rs.getString("f_Data"));
            item.parseStatValues();
            // coll[rs.getRow()] = item;
            coll[i] = item;
            i++;
        }
    }

    public ArrayList<StatData> getArrayList() throws SQLException {
        ArrayList<StatData> listStat = new ArrayList<StatData>();
        // Объект для sql запросов
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("select * from t_Journal;");
        while(rs.next()){
            StatData item = new StatData();
            item.setId(rs.getInt("id"));
            item.setTimestamp(rs.getInt("f_Timestamp"));
            item.setData(rs.getString("f_Data"));
            item.parseStatValues();
            listStat.add(item);
        }
        return listStat;
    }
}
